package com.flink.examples.window;

import com.flink.examples.DataSource;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.List;

/**
 * @Description countWindow数量窗口（滚动窗口【滑动窗口与滚动窗口的区别，在于滑动窗口会有数据元素重叠可能，而滚动窗口不存在元素重叠】）
 * @Author JL
 * @Date 2020/09/15
 * @Version V1.0
 */
public class TumblingCountWindow {

    /**
     * 遍历集合，返回数量滚动窗口下每个性别分区里最大年龄数据记录
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList();
        DataStream<Tuple2<String, Integer>> dataStream = env.fromCollection(tuple3List)
                .map(new MapFunction<Tuple3<String, String, Integer>, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(Tuple3<String, String, Integer> tuple3) throws Exception {
                        return new Tuple2<>(tuple3.f1,tuple3.f2);
                    }
                })
                .returns(Types.TUPLE(Types.STRING,Types.STRING,Types.INT))
                .keyBy((KeySelector<Tuple2<String, Integer>, String>) k ->k.f0)
                //按数量窗口滚动，每3个输入数据流，计算一次
                .countWindow(3)
                //注意：计算变量为f1
                .maxBy(1);
        dataStream.print();
        env.execute("flink CountWindow job");
    }
}
